﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sencha.Serialization.Serializers
{
	public sealed class DateTimeSerializer: TypeSerializer<DateTime>
	{
		public override DateTime Deserialize(IJsonReader reader)
		{
			if (reader.Token == JsonToken.DateTime)
				return reader.Value.AsDateTime;
            
			var dateTimeOffsetStr = reader.ReadString(false);
			var value = DateTime.ParseExact(dateTimeOffsetStr, reader.Context.DateTimeFormats, reader.Context.Format, System.Globalization.DateTimeStyles.AssumeUniversal);
			return value;
		}
		public override void Serialize(IJsonWriter writer, DateTime value)
		{
			var dateTimeFormat = System.Linq.Enumerable.FirstOrDefault(writer.Context.DateTimeFormats);
			var valueStr = value.ToString(dateTimeFormat, writer.Context.Format);
			writer.Write(valueStr);
		}
	}
}
